package cn.ddm.hrm.service.impl;


import cn.ddm.hrm.client.LoginUserClient;
import cn.ddm.hrm.client.ThirdPartyClient;
import cn.ddm.hrm.domain.LoginUser;
import cn.ddm.hrm.domain.VipBase;
import cn.ddm.hrm.domain.VipUser;
import cn.ddm.hrm.dto.RegisterDto;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.mapper.VipBaseMapper;
import cn.ddm.hrm.mapper.VipUserMapper;
import cn.ddm.hrm.service.IVipBaseService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.Constants;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author ldm
 * @since 2022-01-12
 */
@Service
public class VipBaseServiceImpl extends ServiceImpl<VipBaseMapper, VipBase> implements IVipBaseService {
    @Autowired
    private ThirdPartyClient thirdPartyClient;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Autowired
    private VipUserMapper vipUserMapper;

    @Autowired
    private LoginUserClient loginUserClient;

    @Override
//    @Transactional
    @GlobalTransactional
    public AjaxResult register(RegisterDto registerDto) {
        //1校验 null+短信验证码+用户检验
        Map<String,String> params = new HashMap<>();
        params.put("key", Constants.REGISTER_CODE_PREFIX + registerDto.getMobile());
        params.put("code",registerDto.getSmsCode());
        AjaxResult result = thirdPartyClient.verifySmsCode(params);
        ValidUtils.assertBoolean(result.isSuccess(),result.getMessage());
        //2 远程调用hrm-auth保存loginUser并获取到loginId
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(registerDto.getMobile());
        loginUser.setType(1);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String enPass = bCryptPasswordEncoder.encode(registerDto.getPassword());
        loginUser.setPassword(enPass);
        // 调用接口保存
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        Long loginUserId = null;
        if (ajaxResult.isSuccess()) {
            loginUserId = Long.valueOf(ajaxResult.getResultObj().toString());
        }

        //3 保存vipBase，vipuser
        VipBase vipBase = new VipBase();
        vipBase.setPhone(registerDto.getMobile());
        vipBase.setPassword(enPass);
        vipBase.setNickName(registerDto.getMobile());
        vipBase.setBitState(12L);
        vipBase.setLoginId(loginUserId);
        vipBaseMapper.insert(vipBase);

        VipUser vipUser = new VipUser();
        vipUser.setVipId(vipBase.getId());
        vipUserMapper.insert(vipUser);

        return AjaxResult.me();
    }
}
